import { wsEndpoint } from 'api';
import { deepEqual } from 'helpers/object';
import { memo, useEffect } from 'react';
import {
  useRecoilState,
  useRecoilValue,
  useResetRecoilState,
  useSetRecoilState
} from 'recoil';
import io from 'socket.io-client';
// import WebSocket from 'websocket';
import * as WebSocket from 'websocket';
// import WebSocket, { client as WebSocketClient } from 'websocket';
// import { client as WebSocketClient, connection as WebSocketConnection } from 'websocket';
// import * as WebSocket from 'websocket';
// import { client as WebSocketClient, connection as WebSocketConnection } from 'websocket';
import { v4 as uuidv4 } from 'uuid';
import { useAuth } from 'hooks/auth';

import { IAction, actionState } from 'state/action';
import { IUserinfo, userState } from 'state/auth0State';
import {
  IMessage,
  IMessageUpdate,
  IToken,
  askUserState,
  chatSettingsState,
  chatSettingsValueState,
  loadingState,
  voicingState,
  messagesState,
  sessionState,
  tokenCountState
} from 'state/chat';
import { clientState } from 'state/client';
import {
  IElement,
  avatarState,
  elementState,
  tasklistState
} from 'state/element';
import { projectSettingsState } from 'state/project';
import { sessionIdState, userEnvState } from 'state/user';
import { TFormInput } from './organisms/FormInput';
import { isRenderingState,promtStringState } from 'state/chat';

const compareMessageIds = (a: IMessage, b: IMessage) => {
  if (a.id && b.id) return a.id === b.id;
  return false;
};

export default memo(function Socket() {
  const pSettings = useRecoilValue(projectSettingsState);
  const { accessToken, authenticating } = useAuth();
  const userEnv = useRecoilValue(userEnvState);
  const setLoading = useSetRecoilState(loadingState);
  const setVoicing = useSetRecoilState(voicingState);
  const setPromtString= useSetRecoilState(promtStringState);
  const sessionId = useRecoilValue(sessionIdState);
  const [session, setSession] = useRecoilState(sessionState);
  const setMessages = useSetRecoilState(messagesState);
  const setTokenCount = useSetRecoilState(tokenCountState);
  const setAskUser = useSetRecoilState(askUserState);
  const setElements = useSetRecoilState(elementState);
  const setAvatars = useSetRecoilState(avatarState);
  const setTasklists = useSetRecoilState(tasklistState);
  const setActions = useSetRecoilState(actionState);
  const setChatSettings = useSetRecoilState(chatSettingsState);
  const resetChatSettingsValue = useResetRecoilState(chatSettingsValueState);
  const setUser = useSetRecoilState(userState);
  const [isRendering, setIsRendering] = useRecoilState(isRenderingState);

  const queryString = window.location.search;
  const urlParams = new URLSearchParams(queryString);
  const sid = urlParams.get('sid') ?? '';
  const client = useRecoilValue(clientState);

  useEffect(() => {
    console.log('=====>')
      // 模拟我收到一个声音
      // setTimeout(() => {
      //   // new Date().getTime()+
      //   setPromtString("你是谁?")
      // }, 8000);


      

    // if (authenticating || !pSettings) return;

    if (session?.socket) {
      session.socket.removeAllListeners();
      session.socket.close();
    }

    // const client = new WebSocket('ws://example.com');

    // client.on('open', () => {
    //   console.log('WebSocket连接已建立');
    // });

    // client.on('message', (data:any) => {
    //   console.log('收到消息:', data);
    // });

    // return; 



    // 这里作为收声来用！！！长连接
    console.log('wsEndpoint',wsEndpoint)
    const socket = io(wsEndpoint);

    let msgFromJQR = ""
    
    setSession({
      socket
    });

    socket.on('connect', () => {
      console.log('连上了！！！')
      // socket.emit('connection_successful');
      // setSession((s) => ({ ...s!, error: false }));
    });

    // socket.on('connect_error', (err:any) => {
    //   console.error('failed to connect', err);
    //   setSession((s) => ({ ...s!, error: true }));
    // });
    // 接受消息
    socket.on('message', (msg:any) => {
      console.log('zhlie===>')
      if(msg.msg_id =='SPEECH_ISR_ONLY_RESULT_NTF'){
        if(msg.isLast){
          // 发送给数字人
          setPromtString(msgFromJQR)
          msgFromJQR = ""
        }else{
          msgFromJQR +=msg.text;
        }
      }
      if(msg.msg_id =='SPEECH_ISR_WAKEUP_NTF'){
        // 数字人应答一下
        client.setAISay('嗯哼','stream_token')

      }
    });

    // socket.on('task_start', () => {
    //   setLoading(true);
    // });

    // socket.on('task_end', (message:any) => {
    //   setLoading(false);
    //   setVoicing('default')
    // });

    // socket.on('reload', () => {
    //   socket.emit('clear_session');
    //   window.location.reload();
    // });

    // socket.on('new_message', (message: IMessage) => {
    //   if(!isRendering) return
    //   setMessages((oldMessages) => {
    //     const index = oldMessages.findIndex((m) =>
    //       compareMessageIds(m, message)
    //     );
    //     if (index === -1) {
    //       return [...oldMessages, message];
    //     } else {
    //       return [
    //         ...oldMessages.slice(0, index),
    //         message,
    //         ...oldMessages.slice(index + 1)
    //       ];
    //     }
    //   });
    // });

    // socket.on('update_message', (message: IMessageUpdate) => {
    //   setMessages((oldMessages) => {
    //     const index = oldMessages.findIndex((m) =>
    //       compareMessageIds(m, message)
    //     );
    //     if (index === -1) return oldMessages;
    //     if (message.newId) {
    //       message.id = message.newId;
    //       delete message.newId;
    //     }

    //     return [
    //       ...oldMessages.slice(0, index),
    //       message,
    //       ...oldMessages.slice(index + 1)
    //     ];
    //   });
    // });

    // socket.on('delete_message', (message: IMessage) => {
    //   setMessages((oldMessages) => {
    //     const index = oldMessages.findIndex((m) =>
    //       compareMessageIds(m, message)
    //     );

    //     if (index === -1) return oldMessages;
    //     return [
    //       ...oldMessages.slice(0, index),
    //       ...oldMessages.slice(index + 1)
    //     ];
    //   });
    // });

    // socket.on('stream_start', (message: IMessage) => {
    //   setMessages((oldMessages) => [...oldMessages, message]);
    // });

    // socket.on('stop_task', () => {
    //   setIsRendering(false)
    // })

    // socket.on('stream_token', ({ id, token, isSequence }: IToken) => {
    //   if(!isRendering) return
    //   setMessages((oldMessages) => {
    //     const index = oldMessages.findIndex((m) => m.id === id);
    //     if (index === -1) return oldMessages;
    //     const oldMessage = oldMessages[index];
    //     const newMessage = { ...oldMessage };
    //     if (isSequence) {
    //       newMessage.content = token;
    //     } else {
    //       newMessage.content += token;
    //     }
    //     return [
    //       ...oldMessages.slice(0, index),
    //       newMessage,
    //       ...oldMessages.slice(index + 1)
    //     ];
    //   });
    // });

    // socket.on('user_infos', (user: IUserinfo) => {
    //   setUser(user);
    // });

    // socket.on('ask', ({ msg, spec }, callback) => {
    //   setAskUser({ spec, callback });
    //   setMessages((oldMessages) => [...oldMessages, msg]);
    //   setLoading(false);
    //   setVoicing('default')
    // });

    // socket.on('ask_timeout', () => {
    //   setAskUser(undefined);
    //   setLoading(false);
    //   setVoicing('default')
    // });

    // socket.on('clear_ask', () => {
    //   setAskUser(undefined);
    // });

    // socket.on('chat_settings', (inputs: TFormInput[]) => {
    //   setChatSettings((old) => ({ ...old, inputs }));
    //   resetChatSettingsValue();
    // });

    // socket.on('element', (element: IElement) => {
    //   if (element.type === 'avatar') {
    //     setAvatars((old) => [...old, element]);
    //   } else if (element.type === 'tasklist') {
    //     setTasklists((old) => [...old, element]);
    //   } else {
    //     setElements((old) => [...old, element]);
    //   }
    // });

    // socket.on('update_element', (update: { id: string; forIds: string[] }) => {
    //   setElements((old) => {
    //     const index = old.findIndex((e) => e.id === update.id);
    //     if (index === -1) return old;
    //     const element = old[index];
    //     const newElement = { ...element, forIds: update.forIds };
    //     return [...old.slice(0, index), newElement, ...old.slice(index + 1)];
    //   });
    // });

    // socket.on('remove_element', (remove: { id: string }) => {
    //   setElements((old) => {
    //     return old.filter((e) => e.id !== remove.id);
    //   });
    //   setTasklists((old) => {
    //     return old.filter((e) => e.id !== remove.id);
    //   });
    //   setAvatars((old) => {
    //     return old.filter((e) => e.id !== remove.id);
    //   });
    // });

    // socket.on('action', (action: IAction) => {
    //   setActions((old) => [...old, action]);
    // });

    // socket.on('remove_action', (action: IAction) => {
    //   setActions((old) => {
    //     const index = old.findIndex((a) => deepEqual(a, action));
    //     if (index === -1) return old;
    //     return [...old.slice(0, index), ...old.slice(index + 1)];
    //   });
    // });

    // socket.on('token_usage', (count: number) => {
    //   setTokenCount((old) => old + count);
    // });

    // socket.on('audio_client_status', (status) => {
    //     if (status === 'event_wakeup') {
    //       // session?.socket.emit('stop');
    //       setIsRendering(false)
    //     } else if (status === 'event_vad_begin') {
    //       setVoicing('event_vad_begin')
    //     } else if (status === 'event_vad_end') {
    //       setIsRendering(true)
    //       setVoicing('event_vad_end')
    //     }
    // });
  },[userEnv, authenticating, pSettings]);

  return null;
});
